<?php

namespace app\mobile\controller;

use app\admin\model\Admin;
use app\BaseController;
use app\mobile\model\User;
use app\Request;
use think\facade\Validate;

class WechatController extends BaseController
{


    /**添加小程序登陆人员信息
     */
    public function add_user(Request $request){

        $param = $request->param();
        $validate = Validate::rule([
            'user_id|id' => 'require|number',
        ]);
        if (!$validate->check($param)){
            return $this->err_json($validate->getError());
        }

        $user = User::where('id',$param['user_id'])->find();
        $user->name = isset($param['name']) ? $param['name'] : '';
        $user->photo = isset($param['photo']) ? $param['photo'] : '';
        $user->phone = isset($param['phone']) ? $param['phone'] : '';
        //$user->sex = $param['sex'];
        $info = $user->save();

        if ($info == 1){
            return $this->suc_json('添加成功');
        }else{
            return $this->err_json('添加失败');
        }

    }

    /**微信登陆，获取openid，unionid，session_key
     */
    public function wechatLogin(Request $request){

        $js_code = $request->param('code');
        if (empty($js_code)){
            return $this->err_json('请传code参数');
        }

        $grant_type = 'authorization_code';
        $appid = env('wechatmin.app_id');
        $secret = env('wechatmin.secret');

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $js_code . '&grant_type=' . $grant_type;
        $result = $this->CurlGet($url);
        $result = json_decode($result,true);

        if (!empty($result['openid'])){
            $user = User::where('wx_openid', $result['openid'])->find();
            if (empty($user)){
                $user1 = new User();
                $user1->wx_openid = $result['openid'];
                $user1->wx_unionid = isset($result['unionid']) ? $result['unionid'] : '';
                $user2 = $user1->save();
                if ($user2){
                    $user = User::where('id', $user1->id)->find();
                }else{
                    return $this->err_json('登陆失败');
                }
                $result['user_id'] = $user1['id'];
            }else{
                /*$user->wx_unionid = isset($result['unionid']) ? $result['unionid'] : '';
                $user->update_time = date('Y-m-d H:i:s',time());
                $user->save();*/
                $result['user_id'] = $user['id'];
                $result['phone'] = $user['phone'];
                $result['name'] = $user['name'];
                $result['photo'] = $user['photo'];
            }


            if ($user) {
                $token = signToken($user);

                $result['token'] = $token;

                //header('Access-Control-Allow-Origin: *');
                header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept,token");
                header('Access-Control-Allow-Methods: GET, POST, PUT');
                header('Content-Type:application/json; charset=utf-8');
                return $this->suc_json('登陆成功',$result);
            } else {
                return $this->err_json('登陆失败');
                //header('Access-Control-Allow-Origin: *');
                header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept,token");
                header('Access-Control-Allow-Methods: GET, POST, PUT');
                header('Content-Type:application/json; charset=utf-8');
                return json_encode($array);
            }

        }else{
            return $this->err_json('登陆失败');
        }


    }


    /**获取微信用户手机号；
     */
    public function get_phone_number(Request $request){

        $code = $request->param('code');
        if (empty($code)){
            return $this->err_json('code不可为空');
        }

        $access_token = $this->get_min_access_token();
        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $access_token;

        $data = [
            'code' => $code
        ];

        $result = $this->CurlPost($url,json_encode($data));
        $result = json_decode($result,true);

        return $this->suc_json('',$result);

    }

    /**生成小程序签名；
     */
    public function create_min_sign(Request $request){

        $url = $request->param('url');
        if (empty($url)){
            return $this->err_json('url不可为空');
        }

        $noncestr = '!@#$%*&';

        $jsapi_ticket = $this->get_min_ticket();

        $time = time();

        $string = 'jsapi_ticket=' . $jsapi_ticket . '&noncestr=' . $noncestr . '&timestamp=' . $time . '&url=' . $url;

        $signature = sha1($string);

        $info = [
            'timestamp' => $time,
            'nonceStr' => $noncestr,
            'signature' => $signature,
        ];

        return $this->suc_json('',$info);

    }


    /**获取小程序jsapi_ticket;
     */
    public function get_min_ticket(){

        $type = 'jsapi';

        $access_token = $this->get_min_access_token();

        $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $access_token . '&type=' . $type;
        $result = $this->CurlGet($url);
        $result = json_decode($result,true);

        /*if (!empty($result['ticket'])){
            Cache('ticket',$result['ticket'],7100);
        }*/

        return $result['ticket'];

    }


    /**获取小程序接口调用凭据  access_token
     */
    public function get_min_access_token(){
        $grant_type = 'client_credential';
        $appid = env('wechatmin.app_id');
        $secret = env('wechatmin.secret');
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=' . $grant_type . '&appid=' . $appid . '&secret=' . $secret;
        $result = $this->CurlGet($url);
        $result = json_decode($result,true);

        /*if (!empty($result['access_token'])){
            Cache('access_token',$result['access_token'],7100);
        }*/

        return $result['access_token'];

    }



    /**公共的curl方法
     */

    function CurlGet($url){
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
        $res =curl_exec($curl);
        curl_close($curl);
        return $res;

    }


    private function CurlPost($url, $data = array())
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8']);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

}